<?php

class Insiders extends Controller {

    function Insiders()
    {
        parent::Controller();    
        if(!admin_session_check()) redirect('admin/login');
        if(!is_allowed("all")) show_404();
        $this->load->model('usermodel');  
        $this->load->library("form_validation");       
    }     
       
    function index()
    {	
        $this->session->set_flashdata('redirect_page', 'admin/insiders');

		// pagination
		$this->load->library('pagination');
		$config['base_url'] = site_url('admin/insiders/index/');
		$config['total_rows'] = $this->usermodel->admin_get_insiders_count();
		$config['per_page'] = 1000;
		$config["uri_segment"] = 4;
		$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;  
		$total_pages = $config["total_rows"] / $config["per_page"];
	    $config["num_links"] = round($total_pages);
		$this->pagination->initialize($config); 
		$data["pagination_links"] = $this->pagination->create_links();
		$data["total_rows"] = $config['total_rows'];

        $data["list"] = $this->usermodel->admin_get_list('users.id_Users, users.Active_Users, FirstName_UsersDetails, LastName_UsersDetails, Email_UsersDetails', $config["per_page"], $page);
        $data["response"] = get_response();        

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'insiders'));  
        $this->load->view("admin/default/nav_insiders", array('selected' => 'insiders'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/insiders/insiders_list', $data);   
        $this->load->view('admin/default/footer');   

    }  
    function recent()
    {
        $this->session->set_flashdata('redirect_page', 'admin/insiders/recent');

        $data["list"] = $this->usermodel->admin_get_recent();
        $data["response"] = get_response();        

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'insiders'));  
        $this->load->view("admin/default/nav_insiders", array('selected' => 'recent'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/insiders/insiders_recent', $data);   
        $this->load->view('admin/default/footer');   

    }                       
    function preview($id = NULL)
    {
        $this->session->keep_flashdata('redirect_page');
        $this->session->keep_flashdata('insider_search_data');

        $data["item"] = $this->usermodel->admin_get_item($id);
        $data["products"] = $this->usermodel->admin_get_viewed_products_by_user($id);
        $data["crm"] = $this->usermodel->admin_get_crm($id);

        $this->load->model("wishlistsmodel");
        $data["wishlists"] = $this->wishlistsmodel->get_list($id);

        $this->load->view('admin/previews/preview_insiders_template', $data);   
    }                  
    function update_crm()
    {
        $this->session->keep_flashdata('redirect_page');
        $this->session->keep_flashdata('insider_search_data');
        $data["Notes"] = $this->input->post('notes');
        $id = $this->input->post('id');
        $this->usermodel->admin_update_crm($id, $data);
        print "save ok";
    }

    function deactivate($id = false){

        if($id == NULL) show_404();  
        $this->session->keep_flashdata('insider_search_data');
        $users_data = array('Active_Users' => 0);
        $userdetails_data = array('DateDeactivated_UsersDetails' => date("Y-m-d H:i:s"));
        $this->usermodel->admin_update($id, $users_data, $userdetails_data);
        $item = $this->usermodel->admin_get_item($id);
        set_response('success', "User <i>".$item["FirstName_UsersDetails"].' '.$item["LastName_UsersDetails"].'</i> is now inactive. <a href="'.site_url("admin/insiders/preview/".$item["id_Users"]).'" rel="view">Click to view</a>');
        redirect($this->session->flashdata('redirect_page'));
    }
    function activate($id = false){
        
        if($id == NULL) show_404();  
        $this->session->keep_flashdata('insider_search_data');
        $users_data = array('Active_Users' => 1);
        $this->usermodel->admin_update($id, $users_data);
        $item = $this->usermodel->admin_get_item($id);
        set_response('success', "User <i>".$item["FirstName_UsersDetails"].' '.$item["LastName_UsersDetails"].'</i> is now active. <a href="'.site_url("admin/insiders/preview/".$item["id_Users"]).'" rel="view">Click to view</a>');
        redirect($this->session->flashdata('redirect_page'));
    }
    function remove($id = false)
    {

        if($id == NULL) show_404();  

        $item = $this->usermodel->admin_get_item($id);
        if(empty($item)){
            set_response('error', "The user you're attempting to delete does not exist");
            redirect($this->session->flashdata('redirect_page'));
            return;
        }

        $r = '<div style="margin-bottom:10px">';
        $r .= "You're about to permanently delete user <i>".$item['FirstName_UsersDetails'].' '.$item['LastName_UsersDetails'].'</i><br />';
        $r .= 'Note: If you want to block a user from logging in, you should leave it inactive. Once it is removed from the database, the user can create a new account with the same email.';
        $r .= '</div>';
        $r .= '<a class="button" href="'.site_url('admin/insiders/confirm_removal/'.$id).'">CONFIRM DELETION</a>';
        $r .= '<a class="button" href="'.site_url($this->session->flashdata('redirect_page')).'">CANCEL</a>';
        set_response('warning', $r);
        $this->session->keep_flashdata('insider_search_data');   
        redirect($this->session->flashdata('redirect_page'));

    }  
    function confirm_removal($id = false){

        if($id == NULL) show_404();  

        $item = $this->usermodel->admin_get_item($id);
        if(empty($item)){
            set_response('error', "The user you're attempting to delete does not exist");
            $this->session->keep_flashdata('insider_search_data');   
            redirect($this->session->flashdata('redirect_page'));
            return;
        }

        // delete wishlists
        $this->load->model("wishlistsmodel");
        $wishlists = $this->wishlistsmodel->get_list($id);
        foreach($wishlists as $list){
            $this->wishlistsmodel->delete_wishlist_products($list["params"]);
            $this->wishlistsmodel->delete_wishlist($list["params"], $id);
        }
        //delete user
        $this->usermodel->admin_delete($id);

        $this->session->keep_flashdata('insider_search_data');   
        set_response('success', "User <i>".$item['FirstName_UsersDetails'].' '.$item['LastName_UsersDetails']."</i> was deleted.");
        redirect($this->session->flashdata('redirect_page'));
    }

    function search()
    {

        // store the redirection page
        $this->session->set_flashdata('redirect_page', 'admin/insiders/search');
        
        $this->load->library("form_validation");    
		
		$data["limit"] = 200;

        if (($this->input->post("submit_action") !== FALSE) && ($this->_validate_form())){

            $data["string"] = $this->input->post("string");  
            $data["fields"] = $this->input->post("fields");
            $data["order"] = $this->input->post("order");

            //store form data as session vars
            $this->session->set_flashdata('insider_search_data', $data);

            $data["list"] = $this->usermodel->admin_search($data["string"], $data["fields"], $data["order"], $data["limit"]);

        } else if ($this->session->flashdata('insider_search_data')) {

            //get form data from flash data, if it exists
            $this->session->keep_flashdata('insider_search_data');   
            $data = $this->session->flashdata('insider_search_data');
            $data["list"] = $this->usermodel->admin_search($data["string"], $data["fields"], $data["order"], $data["limit"]);

        } else {

            $data["string"] = "";
            $data["fields"] = array('FirstName_UsersDetails', 'LastName_UsersDetails', 'Email_UsersDetails');
            $data["order"] = "DateJoin_UsersDetails";
            $data["list"] = array();

        }   

        $data["response"] = get_response();        

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'insiders'));  
        $this->load->view("admin/default/nav_insiders", array('selected' => 'insiders_search'));
        $this->load->view('admin/insiders/insiders_search', $data);   
        $this->load->view('admin/default/footer');   

    }                       

    private function _validate_form(){
        
        $config = array( 
                        array(
                         'field'   => 'string',
                         'label'   => '"Search for"',
                         'rules'   => 'trim|required|xss_clean'
                        ),
                        array(
                         'field'   => 'fields[]',
                         'label'   => '"Search in"',
                         'rules'   => 'trim|required|xss_clean'
                        ),
                        array(
                         'field'   => 'order',
                         'label'   => '"Order by"',
                         'rules'   => 'trim|required|xss_clean'
                        )
                    );
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }

    public function export(){                                                         
        $this->usermodel->export();
    }    




/*



 
    function edit($id = NULL)
    {
        if($id == NULL) show_404();

        $data["item"] = $this->friendsmodel->admin_get_item($id); 
        if(empty($data["item"])) show_404();

        $this->_process_form();

        $data["action"] = "update";
        $data["token"] = generate_token("friends",720);

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'pages'));  
        $this->load->view("admin/default/nav_pages", array('selected' => 'friends'));
        $this->load->view('admin/friends/friends_form', $data);   
        $this->load->view('admin/default/footer');   

    }
       
    function add()
    {
        $this->_process_form();

        $data["item"] = array(
                "id_Friends" => "",   
                "Title_Friends" => "", 
                "Introduction_Friends" => "",
                "Description_Friends" => "",
                "Image_Friends" => ""
        ); 

        $data["action"] = "create";
        $data["token"] = generate_token("friends",720);

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'pages'));  
        $this->load->view("admin/default/nav_pages", array('selected' => 'friends'));
        $this->load->view('admin/friends/friends_form', $data);   
        $this->load->view('admin/default/footer');   

    } 
    function approve($id = false){

        if(!is_allowed(array(ROLE_ADMIN,ROLE_PUBLISHER))) show_404();
        if($id == NULL) show_404();  

        $data = array('Approved_Friends' => 1, 'Active_Friends' => 1);
        $this->friendsmodel->admin_update($id, $data);
        $item = $this->friendsmodel->admin_get_item($id);
        set_response('success', "Your friend <i>".$item["Title_Friends"].'</i> was approved. <a href="'.site_url("admin/friends/preview/".$item["id_Friends"]).'" rel="view">Click to view</a>');
        redirect('admin/friends');
    }
    function _process_form()
    {        
        if($this->input->post("submit_action") !== FALSE){

            if ($this->_validate_form()) {

                if (validate_token("friends",$this->input->post("token",TRUE))){

                    $data = array(
                        'Title_Friends' => $this->input->post("title"),  
                        'Introduction_Friends' => $this->input->post("introduction"),
                        'Description_Friends' => $this->input->post("description"),
                        'Image_Friends' => $this->input->post("image"),
                    );

                    switch($this->input->post("submit_action")){    

                        case 'create':

                            $new_id = $this->friendsmodel->admin_insert($data);
                            set_response('success','You have a new friend called <i>'.$data['Title_Friends'].'</i>. <a href="'.site_url("admin/friends/preview/".$new_id).'" rel="view">Click to view</a>');

                        break;
                        case 'update':

                            $this->friendsmodel->admin_update($this->input->post("id"), $data);
                            set_response('success','Your friend <i>'.$data['Title_Friends'].'</i> was updated. <a href="'.site_url("admin/friends/preview/".$this->input->post("id")).'" rel="view">Click to view</a>');

                        break;        

                    }

                    redirect("admin/friends");

                }
            }   
        }
    }

    private function _validate_form(){
        
        $config = array( 
                        array(
                         'field'   => 'title',
                         'label'   => 'Title',
                         'rules'   => 'trim|required|xss_clean|callback_check_duplicated|max_length[250]'
                        ),
                        array(
                         'field'   => 'introduction',
                         'label'   => 'Introduction',
                         'rules'   => 'trim|required|xss_clean'
                        ),
                        array(
                         'field'   => 'description',
                         'label'   => 'Description',
                         'rules'   => 'trim|required|xss_clean'
                        ),             
                        array(
                         'field'   => 'image',
                         'label'   => 'Image',
                         'rules'   => 'trim|xss_clean'
                        )
                    );
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }

     public function check_duplicated($name){ 

        $id = $this->input->post("id");

        if($this->friendsmodel->is_duplicated('Title_Friends',$name,$id)){
            $this->form_validation->set_message('check_duplicated', "You already have a friend with that name.");
            return FALSE;
        }else{
            return TRUE;    
        }
    } 
  */
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */
